package com.amazon.web.controller;


import com.amazon.bo.Product;
import com.amazon.bo.UserSession;
import com.amazon.service.I18nService;
import com.amazon.web.controller.vo.ClientEunm;
import com.amazon.web.controller.vo.productResult;
import com.amazon.web.util.*;
import com.amazon.service.ProductService;

import com.translate.TransApi;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.amazon.web.model.account.LoginResult;
import com.amazon.service.SMSCodeService;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.amazon.web.util.EncryptionUtil;

import javax.annotation.Resource;

import javax.annotation.Resource;

@RestController
@RequestMapping(value="product")
public class ProductController {
    @Value("${is.open.cms}")
    public String isOpenCms;


    private static final String APP_ID = "20180715000185622";
    private static final String SECURITY_KEY = "RtGMlsmDQUDfmQ6Ddi5L";

    @Resource
    private OSSManageUtil ossManageUtil;

    @Resource
    ProductService productService;

    @Autowired
    I18nService i18nService;

    @Resource
    SMSCodeService codeservicem;

    @RequestMapping(value = "productlist", method = RequestMethod.POST)
    public Object getGoodsList(int start, int length, int draw,String conn) {
        productResult result = new productResult();

        int total = productService.getProductsCount(StringUtils.isBlank(conn)?"": conn);

        result.setData(productService.getProductListForDeal(conn,start, length));
        result.setDraw(draw);
        result.setRecordsTotal(total);
        result.setRecordsFiltered(total);

        return result;

    }

    @RequestMapping(value = "productdetail", method = RequestMethod.POST)
    public ApiResponse getGoodsByid(String goodsid) {
        String pid = goodsid;
        Product p = productService.getById(Integer.parseInt(goodsid));
        return ResponseUtil.getSuccessResponse(p, 1);
    }











    @RequestMapping(value="add",method =RequestMethod.POST)
    public Object addProduct(String url ,String title,String cross,String img,String memo,String attr,
                             String category,String stock,String price,String ukid,String weight,String Props,String shipfee,String designer,String bigclass){



        String newProps=Props.replace("颜色:\n","");

        newProps=newProps.replace("\n",";");
        newProps=newProps.split("尺码:")[0];
        Product p = new Product();
        p.setProps(newProps);
        String[] strs = url.split(".html")[0].split("/");

        p.setSKU(strs[strs.length-1]);

        p.setSkuUrl(url);
        p.setBigImg(img.replace("|",","));
        p.setSmallImgs(img.replace("|",","));



        p.setChTitle(title);
        String[] memos=memo.split(";");

        String bulletPoint = "";
        String bullets="";
        for(int i=0;i<5;i++){
            bulletPoint+=memos[i]+"\n";
            bullets+=";";
        }

        for(int i=0;i<memos.length;i++){
            String tmp[]=memos[i].split(":");
            if(tmp.length==2) {
                switch (tmp[0]){
                    case "适用性别":{
                        if(p.getForpeople()==null || p.getForpeople().equals("null")) {
                            p.setForpeople(tmp[1]);
                        }else{
                            p.setForpeople(p.getForpeople()+"/"+tmp[1]);
                        }
                        break;
                    }
                    case "适用年龄段":{
                        if(p.getForpeople()==null || p.getForpeople().equals("null")) {
                            p.setForpeople(tmp[1]);
                        }else{
                            p.setForpeople(p.getForpeople()+"/"+tmp[1]);
                        }
                        break;
                    }
                    case "产地":{
                        p.setOrigin(tmp[1]);
                        break;
                    }
                    case "材质":{
                        p.setProductMaterial(tmp[1]);
                    }
                }
            }
        }
        String des ="";
        for(int i=0;i<memos.length;i++){
            des+=memos[i]+"\n";
        }
        p.setStock(Integer.parseInt(stock));//库存
        p.setShippingWeight(weight);
        p.setMSRP(price);//进价
        p.setProductClass(ukid);//分类
        if(shipfee==null){
            shipfee="20";
        }
        p.setShipfee(Double.parseDouble(shipfee));//运费
        p.setDesigner(designer);//厂商
        p.setBigClass(Integer.parseInt(bigclass));//站内分类
        p.setChDescription(des);
        p.setChBulletPoint(bulletPoint);
        p.setCategoryName(category);
        p.setCross(cross);
        p.setAttr(attr);
        p.setProductStatus(1);






        TransApi api = new TransApi(APP_ID, SECURITY_KEY);


        //描述
        //中文
        p.setChDescription(des);

        Map<String, Object> result=null;
        List<Map<String, Object>> list = null;

        if(des!=null) {



            result = Tools.parserJson2Map(api.getTransResult(memo, "auto", "en"));
            list = (List<Map<String, Object>>) result.get("trans_result");
            String enDes = list.get(0).get("dst").toString();

            String enDeses="";
            String[] ens =enDes.split(";");
            for(int i=0;i<ens.length;i++){
                enDeses+=ens[i]+"\n";
            }
            p.setDescription(enDeses);

             /*
            //法国
            result = Tools.parserJson2Map(api.getTransResult(des, "auto", "fra"));
            list = (List<Map<String, Object>>) result.get("trans_result");
            p.setFrDescription(list.get(0).get("dst").toString());

            //德国
            result = Tools.parserJson2Map(api.getTransResult(des, "auto", "de"));
            list = (List<Map<String, Object>>) result.get("trans_result");
            p.setDeDescription(list.get(0).get("dst").toString());

            //意大利
            result = Tools.parserJson2Map(api.getTransResult(des, "auto", "it"));
            list = (List<Map<String, Object>>) result.get("trans_result");
            p.setItDescription(list.get(0).get("dst").toString());

            //西班牙
            result = Tools.parserJson2Map(api.getTransResult(des, "auto", "spa"));
            list = (List<Map<String, Object>>) result.get("trans_result");
            p.setEsDescription(list.get(0).get("dst").toString());

            //日本
            result = Tools.parserJson2Map(api.getTransResult(des, "auto", "jp"));
            list = (List<Map<String, Object>>) result.get("trans_result");
            p.setJpDescription(list.get(0).get("dst").toString());
            */
        }

        //标题
        title = p.getChTitle();
        p.setChTitle(title);

        if(title!=null) {
            //英文
            result = Tools.parserJson2Map(api.getTransResult(title, "auto", "en"));
            list = (List<Map<String, Object>>) result.get("trans_result");



            p.setTitle(list.get(0).get("dst").toString());

            /*
            //法国
            result = Tools.parserJson2Map(api.getTransResult(title, "auto", "fra"));
            list = (List<Map<String, Object>>) result.get("trans_result");
            p.setFrTitle(list.get(0).get("dst").toString());

            //德国
            result = Tools.parserJson2Map(api.getTransResult(title, "auto", "de"));
            list = (List<Map<String, Object>>) result.get("trans_result");
            p.setDeTitle(list.get(0).get("dst").toString());

            //意大利
            result = Tools.parserJson2Map(api.getTransResult(title, "auto", "it"));
            list = (List<Map<String, Object>>) result.get("trans_result");
            p.setItTitle(list.get(0).get("dst").toString());

            //西班牙
            result = Tools.parserJson2Map(api.getTransResult(title, "auto", "spa"));
            list = (List<Map<String, Object>>) result.get("trans_result");
            p.setEsTitle(list.get(0).get("dst").toString());

            //日本
            result = Tools.parserJson2Map(api.getTransResult(title, "auto", "jp"));
            list = (List<Map<String, Object>>) result.get("trans_result");
            p.setJpTitle(list.get(0).get("dst").toString());
            */
        }

        //要点


        String bullet =memo;
        if (bullet != null && bullet.length()>0) {

            //英文
            result = Tools.parserJson2Map(api.getTransResult(bullet, "auto", "en"));
            list = (List<Map<String, Object>>) result.get("trans_result");

            String enBullet = list.get(0).get("dst").toString();

            String[] enBullets = enBullet.split(";");

            String enBulletEs="";

            int max = 5;
            if(enBullets.length<max){
                max=enBullets.length-1;
            }
            for(int i =0 ;i<max;i++){
                enBulletEs+=enBullets[i]+"\n";
            }

            p.setBulletPoint(enBulletEs);


            /*
            //法国
            result = Tools.parserJson2Map(api.getTransResult(bullet, "auto", "fra"));
            list = (List<Map<String, Object>>) result.get("trans_result");
            p.setFrBulletPoint(list.get(0).get("dst").toString());

            //德国
            result = Tools.parserJson2Map(api.getTransResult(bullet, "auto", "de"));
            list = (List<Map<String, Object>>) result.get("trans_result");
            p.setDeBulletPoint(list.get(0).get("dst").toString());

            //意大利
            result = Tools.parserJson2Map(api.getTransResult(bullet, "auto", "it"));
            list = (List<Map<String, Object>>) result.get("trans_result");
            p.setItBulletPoint(list.get(0).get("dst").toString());

            //西班牙
            result = Tools.parserJson2Map(api.getTransResult(bullet, "auto", "spa"));
            list = (List<Map<String, Object>>) result.get("trans_result");
            p.setEsBulletPoint(list.get(0).get("dst").toString());

            //日本
            result = Tools.parserJson2Map(api.getTransResult(bullet, "auto", "jp"));
            list = (List<Map<String, Object>>) result.get("trans_result");
            p.setJpBulletPoint(list.get(0).get("dst").toString());

            */

        }

        //关键词
        String term = p.getChSearchTerms();
        if (term != null) {

            //英文
            result = Tools.parserJson2Map(api.getTransResult(term, "auto", "en"));
            list = (List<Map<String, Object>>) result.get("trans_result");
            p.setSearchTerms(list.get(0).get("dst").toString());

            /*
            //法国
            result = Tools.parserJson2Map(api.getTransResult(term, "auto", "fra"));
            list = (List<Map<String, Object>>) result.get("trans_result");
            p.setFrSearchTerms(list.get(0).get("dst").toString());

            //德国
            result = Tools.parserJson2Map(api.getTransResult(term, "auto", "de"));
            list = (List<Map<String, Object>>) result.get("trans_result");
            p.setDeSearchTerms(list.get(0).get("dst").toString());

            //意大利
            result = Tools.parserJson2Map(api.getTransResult(term, "auto", "it"));
            list = (List<Map<String, Object>>) result.get("trans_result");
            p.setItSearchTerms(list.get(0).get("dst").toString());

            //西班牙
            result = Tools.parserJson2Map(api.getTransResult(term, "auto", "spa"));
            list = (List<Map<String, Object>>) result.get("trans_result");
            p.setEsSearchTerms(list.get(0).get("dst").toString());

            //日本
            result = Tools.parserJson2Map(api.getTransResult(term, "auto", "jp"));
            list = (List<Map<String, Object>>) result.get("trans_result");
            p.setJpSearchTerms(list.get(0).get("dst").toString());
             */
        }
        productService.addProduct(p);
        return p;


    }
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String update(String goodsid,String amzonprice,String onlineday) {
        String d;
       Boolean b= productService.productupdate(Integer.parseInt(goodsid),Double.parseDouble(amzonprice),onlineday);
       return "更新成功";
    }




    @RequestMapping(value="getPurchaseProductList",method =RequestMethod.GET)
    public ApiResponse getshopList(int status,String pSource,String pname,int page, int pagesize) {
        StringBuilder conn=new StringBuilder("");
        //产品状态
        if(status!=0){
            conn.append(" and  product_status="+status);
        }
        //产品来源
        if(!pSource.equals("")){
            conn.append(" and  sku_url like '%"+pSource+"%' ");
        }
        //产品名称
        if(!pname.equals("")){
            conn.append(" and  ch_title like '%"+pname+"%' ");
        }

        List<Product> list=productService.getProductList(conn.toString(),page,pagesize);
        for (Product p: list) {
            if(p.getSmallImgs().length()>0 && p.getSmallImgs().indexOf(",")>0){
                p.setSmallImgs(p.getSmallImgs().substring(0,p.getSmallImgs().indexOf(",")));
            }
        }
        int total = productService.getProductsCount(conn.length()==0?"": conn.toString().substring(4));
        return ResponseUtil.getSuccessResponse(list, total);
    }

    @RequestMapping(value="productChangeStatus",method =RequestMethod.POST)
    public Object productChangeStatus(String pids,int status){
        String[] ids=pids.split(",");
        for (String id: ids) {
            boolean f=productService.productChangeStatus(Integer.parseInt(id),status);
        }
        return "true";
    }


    @RequestMapping(value="productChangeImg",method =RequestMethod.POST)
    public Object productChangeImg(String pid,String img,int status,String colors){

//        String[] collist=colors!=""?colors.split(";"):null;
//        String newColors="";
//        for (String c : collist) {
//            try {
//                if(c.length()>10) {
//                    String imgurl = c.split(",")[1].replace("imageUrl:", "");
//                    if (img.contains(imgurl)) {
//                        newColors += c + ";";
//                    }
//                }
//            } catch (Exception ex) {
//                return false;
//            }
//        }
//        if(newColors.length()>0){
//            newColors=newColors.substring(0,newColors.length()-1);
//        }
        boolean f=productService.productChangeImg( Integer.parseInt(pid),img,status,colors);
        return f;
    }

    @RequestMapping(value="productChangeAttr",method =RequestMethod.POST)
    public Object productChangeAttr(Product p){
        boolean f=productService.productChangeAttr(p);
        return f;
    }



    @RequestMapping(value="productChangeDesc",method =RequestMethod.POST)
    public Object productChangeDesc(int id,int productStatus,String BulletPoint,String Description,String SearchTerms,String Title,String contry){
        boolean f=productService.productChangeDesc(id,productStatus, BulletPoint,Description,SearchTerms,Title,contry);
        return f;
    }


    @RequestMapping(value="trans",method =RequestMethod.POST)
    public Object trans(String query,String from, String to){

        if(query==null || query.length()==0){
            return "";
        }
        TransApi api = new TransApi(APP_ID, SECURITY_KEY);

        Map<String,Object>    result = Tools.parserJson2Map(api.getTransResult(query, from, to));
        List<Map<String, Object>>  list = (List<Map<String, Object>>) result.get("trans_result");

        return list.get(0).get("dst").toString().replace(";","\n");
    }

    @RequestMapping(value="translate",method =RequestMethod.POST)
    public Object translate(String bulletPoint,String description,String searchTerms,String title,String from,String to){


        Map<String,Object> result = new HashMap<>();
        result.put("bulletPoint",trans(bulletPoint,from,to));

        result.put("description",trans(description,from,to));

        result.put("searchTerms",trans(searchTerms,from,to));

        result.put("title",trans(title,from,to));

         return result;
    }

    @RequestMapping(value="updateChdesc",method =RequestMethod.POST)
    public Object updateChdesc(String item,String oriv,String repv){

        boolean flag=productService.updateChDesc(item,oriv,repv);
        return flag;
    }
    @RequestMapping(value="getPublishList",method =RequestMethod.GET)
    public ApiResponse getPublishList(int shopid,String  sku,String title,int page, int pagesize){

        Object list=productService.getPublishList(shopid,sku,title,page,pagesize);
        List<Map<String,Object>> newlist=(List<Map<String,Object>>) list;
        if(newlist.size()>0){
            for (Map<String,Object> mp:
                    newlist) {
                String img=mp.get("big_img").toString();
                mp.put("big_img",img.split(",")[0]);
            }
        }
        int total = productService.getPublicCount(shopid,sku,title);
        return ResponseUtil.getSuccessResponse(list, total);
    }

}
